﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using SIG.Model;
using SIG.Service;
using PagedList;

using AutoMapper;
using SIG.Infrastructure.Configs;
using SIG.ViewModel;
using SIG.Model.Enums;
using SIG.WebMVC.Filters;
using SIG.Infrastructure.Helper;
using SIG.ViewModel.Admin.Pages;
using System.Xml.Linq;
using SIG.InputModel.Admin.Pages;
using SIG.Resources.Admin;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class PageController : BaseController
    {
        private readonly IPageService _pageService;
        private readonly IPageMetaService _pageMetaService;
        private IMapper _mapper;
        public PageController(IPageService pageService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _pageService = pageService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;


        }

        // GET: Admin/Pages
        public ActionResult Index(int? page, string keyword)
        {
            PageListVM pageListVM = GetElements(page, keyword);

            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(pageListVM);        

        }

        private PageListVM GetElements(int? page, string keyword)
        {
            var pageListVM = new PageListVM();

            pageListVM.Keyword = keyword;
            pageListVM.PageIndex = (page ?? 1) - 1;
            pageListVM.PageSize = SettingsManager.Page.PageSize;
            int totalCount;
            var pagelist = _pageService.GetPagedElements(pageListVM.PageIndex, pageListVM.PageSize, pageListVM.Keyword, out totalCount);
            var pageVMList = _mapper.Map<List<Page>, List<PageVM>>(pagelist);
            pageListVM.TotalCount = totalCount;
            pageListVM.Pages = new StaticPagedList<PageVM>(pageVMList, pageListVM.PageIndex + 1, pageListVM.PageSize, pageListVM.TotalCount); ;
            return pageListVM;
        }
        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/PageSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        // GET: Admin/Pages/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            
            Page page = _pageService.GetById(id);
            if (page == null)
            {
                return HttpNotFound();
            }
            return View(page);
        }

        // GET: Admin/Pages/Create
        public ActionResult Create()
        {
            PageIM page = new PageIM()
            {                
                Active = true
            };
            return PartialView("_Create",page);
        }

     
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public JsonResult Create(PageIM page)
        {
            if (!ModelState.IsValid)
            {
                AR.SetSuccess(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
              
                var newPage = _mapper.Map<PageIM, Page>(page);
                _pageService.Create(newPage);

                if (!string.IsNullOrEmpty(page.Keywords) || !string.IsNullOrEmpty(page.SEODescription))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newPage.Id,
                        Keyword = page.Keywords.Replace('，', ','),
                        Description = page.SEODescription,
                        ModelType = ModelType.PAGE
                    };
                    _pageMetaService.Create(pageMeta);
                }

                int count;
                int pageSize = SettingsManager.Page.PageSize;
                var list = _pageService.GetPagedElements(0, pageSize, string.Empty, out count);
                List<PageVM> pageList = _mapper.Map<List<Page>, List<PageVM>>(list);
                AR.Data = RenderPartialViewToString("_PageList", pageList);

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Page));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
                   
        }

        // GET: Admin/Pages/Edit/5
        public ActionResult Edit(int id)
        {
          

            Page page = _pageService.GetById(id);
            if (page == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
               // return HttpNotFound();
            }

            var editPage = _mapper.Map<Page, PageIM>(page);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.PAGE, editPage.Id);
            if (pageMeta != null)
            {
                editPage.Keywords = pageMeta.Keyword;
                editPage.SEODescription = pageMeta.Description;
            }
                       
            return PartialView("_Edit",editPage);
           
        }

     
        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Edit(PageIM page)
        {
            if (!ModelState.IsValid)
            {   
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                //  var editPage = _mapper.Map<PageIM, Page>(page);

                var editPage = _pageService.GetById(page.Id);
                editPage.Title = page.Title;
                editPage.Body = page.Body;
                editPage.Active = page.Active;
                editPage.SeoName = page.SeoName;

                _pageService.Update(editPage);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.PAGE, editPage.Id);
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(page.Keywords) || !string.IsNullOrEmpty(page.SEODescription))
                {

                    pageMeta.ObjectId = page.Id;
                    pageMeta.Keyword = page.Keywords.Replace('，',',');
                    pageMeta.Description = page.SEODescription;
                    pageMeta.ModelType = ModelType.PAGE;

                    if (pageMeta.Id > 0)
                    {
                        _pageMetaService.Update(pageMeta);
                    }
                    else
                    {
                        _pageMetaService.Create(pageMeta);
                    }
                }

                var pageVM = _mapper.Map<PageVM>(editPage);

                AR.Id = page.Id;
                AR.Data = RenderPartialViewToString("_PageItem", pageVM);

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Page));            
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

          
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {
            Page page = _pageService.GetById(id);
            if (page == null)
            {
                AR.Setfailure(String.Format(Messages.AlertUpdateSuccess, EntityNames.Page));
                return Json(AR, JsonRequestBehavior.DenyGet);

                
            }
           

            try
            {

                page.Active = !page.Active;
                _pageService.Update(page);
                           
                var vm = _mapper.Map<PageVM>(page);
                AR.Data = RenderPartialViewToString("_PageItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Page));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {
            Page page = _pageService.GetById(id);           
            if (page != null)
            {
                _pageService.Delete(page);

                AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Page));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            AR.Setfailure(String.Format(Messages.AlertDeleteFailure, EntityNames.Page));
            return Json(AR, JsonRequestBehavior.DenyGet);
          
        }

        public JsonResult IsSeoNameUnique(string SeoName, int? Id)
        {
            return !IsExist(SeoName, Id)
                ? Json(true, JsonRequestBehavior.AllowGet)
                : Json(false, JsonRequestBehavior.AllowGet);
        }
        public bool IsExist(string SeoName, int? id)
        {
            if (id > 0)
            {
                var wType = _pageService.FindBy(w => w.SeoName == SeoName && w.Id != id).ToList();
                if (wType.Count > 0)
                    return true;

                return false;
            }
            else
            {
                var wType = _pageService.FindBy(w => w.SeoName == SeoName).ToList();
                if (wType.Count > 0)
                    return true;

                return false;
            }           
           
        }
    }
}
